<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/4/26
 * Time: 14:33
 * Desc: 商品配放管理
 */
namespace app\kuguan\controller;
use controller\BasicAdmin;
use service\DataService;
use think\Db;
use app\kuguan\model\GoodsPeifangYongliao;

class Peifang extends BasicAdmin{
    /**
     * @Author  lingyun
     * @Desc    原料库存日志记录、
     * 2018-04-26
     */
    public function index(){
        $this->title = "配方";
        $table = 'GoodsPeifang';
        $get = $this->request->get();
        $map = [];
        $map['is_deleted'] = ['eq',0];
        $map['store_id'] = ['eq',0];
        if(isset($get['name']) && !empty($get['name'])){
            $map['title'] = ['like','%'.$get['name'].'%'];
        }

        $db = db('goods_peifang')->where($map)->order('id desc');
        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    添加 -- 编辑
     */
    public function add_edit(){
        if(request()->isPost()){
            $post = input('post.');
            if(empty($post['id'])){
                $code = db('goods_peifang')->where('code',$post['code'])->find();
                if(!empty($code)){
                    $this->error('编号已被占用，请重新填写','');
                }
            }else{
                $code = db('goods_peifang')->where(['code'=>['eq',$post['code']],'id'=>['neq',$post['id']]])->find();
                if(!empty($code)){
                    $this->error('编号已被占用，请重新填写','');
                }
            }
            if(empty($post['id'])){
                $post['update_time'] = time();
                $post['create_time'] = time();
                $flag = db('goods_peifang')->insert($post);
                $flag>0?$this->success('保存成功',''):$this->error('保存失败','');
            }else{
                $post['update_time'] = time();
                $flag= db('goods_peifang')->update($post);
                $flag!==false?$this->success('保存成功',''):$this->error('保存失败','');
            }
        }else{
            $id = input('id');
            $info = db('goods_peifang')->where('id',$id)->find();

            $this->assign('info',$info);
            return $this->fetch('a_e_peifang');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    删除配方
     * 2018-05-30
     */
    public function del_peifang(){
        $id = input('id');
        $res = db('goods_peifang')->where('id',$id)->update(['is_deleted'=>1]);
        $res!==0?$this->success('删除成功',''):$this->error('删除失败','');
    }

    /**
     * @Author  lingyun
     * @Desc    导出原料库存日志
     * 2018-04-26
     */
    public function export_material_stock_log(){
        $post = input('param.');
        $model = new MaterialStockModel();
        $model->export_material_stock_log($post);
    }

    /**
     * @Author  lingyun
     * @Desc    添加编辑配方
     * 2018-04-26
     */
    public function add_edit_peifang(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $data = $this->create_data_arr($post);

            db('goods_peifang_yongliao')->where(['p_id'=>$post['p_id']])->update(['is_deleted'=>1]);
            $model = new GoodsPeifangYongliao();
            $res = $model->saveall($data['data']);
            db('goods_peifang')->where('id',$post['p_id'])->update(['chengben'=>$data['chengben'],'chengben_price'=>$data['chengben_price']]);
            $this->success('保存成功',url('@admin').'#'.url('Peifang/index').'?spm='.input('spm'));
        }else{
            $id = input('id');          //ys_goods_peifang --- id           //商品属性id
//            $peifang = db('goods_peifang')->alias('a')->join('goods_peifang_yongliao b','a.id=b.p_id','LEFT')->where(['a.id'=>$id,'b.is_deleted'=>0])->field('a.*,sum(b.s_use_g) as yongliao')->find();
            $peifang = db('goods_peifang')->where('id',$id)->find();
            $yongliao = db('goods_peifang_yongliao')->alias('a')->join('ys_goods_material b','a.m_id=b.id','LEFT')->where(['a.p_id'=>$id,'b.is_signal'=>0,'a.is_deleted'=>0])->sum('a.s_use_g');
            $peifang['yongliao'] = $yongliao;
//            $goods = db('goods_spec_detail')->where('id',$id)->find();
            $list = db('goods_peifang_yongliao')->alias('a')->join('goods_material b','a.m_id=b.id','LEFT')->where(['a.p_id'=>$id,'a.is_deleted'=>0])->field('a.*,b.price')->select();
            $num = count($list);

            $material = db('goods_material')->where(['is_deleted'=>0,'store_id'=>0])->select();

            $this->assign('id',$id);
//            $this->assign('goods',$goods);
            $this->assign('peifang',$peifang);
            $this->assign('num',$num);
            $this->assign('title','编辑配方 -- '.$peifang['title']);
            $this->assign('list',$list);                //用料详情
            $this->assign('material',$material);        //原材料
            if(!empty($list)){
                $this->assign('url',url('Peifang/update_peifang'));        //保存配方
            }else{
                $this->assign('url',url('Peifang/add_edit_peifang'));      //保存配方
            }

            return $this->fetch('add_edit_peifang');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    更新配方
     * 2018-05-24
     */
    public function update_peifang(){
        $post = input('post.');
        $data  =$this->create_data_arr($post);
        $model = new GoodsPeifangYongliao();
        $model->saveall($data['data']);         //更新配方数据
        db('goods_peifang')->where('id',$post['p_id'])->update(['chengben'=>$data['chengben'],'chengben_price'=>$data['chengben_price']]);
        $this->success('保存成功',url('@admin').'#'.url('Peifang/index').'?spm='.input('spm'));
    }
    /**
     * @Author      lingyun
     * @DateTime    2018-05-04
     * @Description 创建入库数据
     * @return      [type]     [description]
     */
    private function create_data_arr($post){
        // halt($post);
        $p_id = $post['p_id'];
        unset($post['p_id']);
        unset($post['sign']);
        $m_id = $post['m_id'];
        $data = array();
        $chengben = 0;
        $chengben_price = 0;
        foreach($m_id as $k => $v){
            if(isset($post['ids'])){
                if(isset($post['ids'][$k])){
                    $data[$k]['id'] = $post['ids'][$k];
                }
            }
            $data[$k]['p_id'] = $p_id;
            $data[$k]['m_id'] = $v;
            $data[$k]['p_use_kg'] = $post['s_use_g'][$k]/1000;
            $data[$k]['p_use_g'] = $post['s_use_g'][$k];
            $data[$k]['s_use_g'] = $post['s_use_g'][$k];
            $data[$k]['loss'] = $post['loss'][$k];
            $data[$k]['chengben'] = $post['chengben'][$k];
            $data[$k]['chengben_price'] = $post['chengben_price'][$k];
            $data[$k]['is_deleted'] = 0;
            $data[$k]['create_time'] = time();
            $data[$k]['update_time'] = time();
            $chengben+=$post['chengben'][$k];
            $chengben_price+=$post['chengben_price'][$k];
        }
        return ['data'=>$data,'chengben'=>$chengben,'chengben_price'=>$chengben_price];
    }

    /**
     * @Author      Hybrid
     * @DateTime    2018-05-04
     * @Description 保存属性
     * @return      [type]     [description]
     */
    public function savespec(){
        $post = input('post.');
        $res = db('goods_peifang_yongliao')->where('id',$post['id'])->update(['material_id'=>$post['material_id'],'num'=>$post['num']]);
        $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
    }

    /**
     * @Author      Hybrid
     * @DateTime    2018-05-04
     * @Description 删除用料
     * @return      [type]     [description]
     */
    public function delspec(){
        $post = input('post.');
        $res = db('goods_peifang_yongliao')->where('id',$post['id'])->update(['is_deleted'=>1]);
        $res!==false?$this->success('删除成功',''):$this->error('删除失败','');
    }

    /**
     * @Author      Hybrid
     * @DateTime    2018-05-04
     * @Description 商品库存
     * @return      [type]     [description]
     */
    public function goods_stock(){
        $this->title = "商品库存";
        $table = 'Goods';
        $get = $this->request->get();
        $map = [];
        $map['a.is_deleted'] = ['eq',0];
        $map['a.store_id'] = ['eq',0];
        $map['b.is_deleted'] = ['eq',0];
        if(!empty($get['name'])){
            $map['name'] = ['like','%'.$get['name'].'%'];
            $this->assign('name',$get['name']);
        }else{
            $this->assign('name','');
        }

        $db = db('goods')->alias('a')->join('ys_goods_spec_detail b','a.id=b.goods_id','LEFT')->where($map)->field('a.*,b.title,b.stock,b.id as goods_spec_id')->order('a.id desc');
        return parent::_list($db);
    }

    /**
     * @Author      Hybrid
     * @DateTime    2018-05-04
     * @Description 商品库存
     * @return      [type]     [description]
     */
    public function goods_stock_log(){
        $id = input('id');
        $db = db('goods_stock_log')->alias('a')->join('ys_store b','a.store_id=b.id','LEFT')->join('ys_goods c','a.goods_id=c.id','LEFT')->field('a.*,c.name,b.title')->where('a.goods_spec_id',$id)->order('a.id desc');
        $get = input('get.');
        if(isset($get['date']) && $get['date'] !== '') {
            list($start, $end) = explode(' - ', $get['date']);
            $start = $start."  00:00:00";       $end = $end." 23:59:59";
            $start = strtotime($start);         $end = strtotime($end);
            $db->whereBetween('a.addtime',["{$start}", "{$end}"]);
        }

        return parent::_list($db);
    }

    /**
     * @Author      Hybrid
     * @DateTime    2018-05-04
     * @Description 变更库存
     * @return      [type]     [description]
     */
    public function change_stock(){
        if(request()->isPost()){
            $post = input('post.');

            $stock = Db::name('goods_spec_detail')->where(['goods_id'=>$post['goods_id'],'id'=>$post['goods_spec_id']])->value('stock');            //商品库存
            // halt($stock);
            unset($post['goods_name']);
            // $model = new GoodsStockLog();
            if($post['sign'] == 1){
                $post['cur_num'] = $post['rec_num']+$stock;     //当前库存
            }else{
                $post['cur_num'] = $stock-$post['dif_num'];     //当前库存
            }
            $post['addtime'] = time();
            if($post['sign'] == 1){
                $post['dif_num'] = $post['rec_num'] - $post['del_num'];         //差异数
            }
            empty($post['goods_spec_id'])?$post['goods_spec_id']=0:$post['goods_spec_id'];
            $post['sign']==1?$post['type']=1:$post['type']=2;       //1增加，2减少
            $res = Db::name('goods_stock_log')->insertGetId($post);
            if($res > 0){
                if($post['sign'] == 1){
                    $res = Db::name('goods_spec_detail')->where('id',$post['goods_spec_id'])->setInc('stock',$post['rec_num']);
                }else{
                    $res = Db::name('goods_spec_detail')->where('id',$post['goods_spec_id'])->setDec('stock',$post['dif_num']);
                }
            }else{
                $this->error('保存失败','');
            }
            $res!==false?$this->success('保存成功',url('@admin').'#'.url('Peifang/goods_stock').'?spm='.input('spm')):$this->error('保存失败','');
        }else{
            $goods_id = input('goods_id');      //商品ID
            $goods_spec_id = input('goods_spec_id');        //商品属性id
            $goods = Db::name('goods')->where('id',$goods_id)->find();      //商品名称
            $goods_spec = Db::name('goods_spec_detail')->where(['id'=>$goods_spec_id,'is_deleted'=>0])->find(); //商品属性
            $this->assign('goods_spec',$goods_spec);
            $this->assign('goods_id',$goods_id);        //商品ID
            $this->assign('goods_spec_id',$goods_spec_id);
            $this->assign('title','变更库存');
            $this->assign('goods',$goods);
            return $this->fetch('change_stock');
        }
    }




}